﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Configuration;
using Nop.Services.Configuration;

namespace Nop.Services.Shipping
{
    public class ZipPostalCodeService : IZipPostalCodeService
    {
        private readonly AddressSettings _addressSettings;

        public ZipPostalCodeService(AddressSettings addressSettings)
        {
            _addressSettings = addressSettings;
        }

        public bool Validate(string zipPostalCode)
        {
            var regex = new Regex(@"^ *[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[A-Za-z]{1} *\d{1}[A-Za-z]{1}\d{1} *$");

            return regex.IsMatch(zipPostalCode);
        }

        public bool ValidateIsContain(string zipPostalCode)
        {
            if (string.IsNullOrEmpty(zipPostalCode)) return false;

            var value = GetZipPostalCodePrefixValue();

            return value != null && Validate(value, zipPostalCode);
        }

        private IEnumerable<string> GetZipPostalCodePrefixValue()
        {
            var value = _addressSettings.ZipPostalCodePrefixValue;

            return string.IsNullOrEmpty(value) ? null : value.Split(',').ToList();
        }

        private static bool Validate(IEnumerable<string> validateVale, string zipPostalCode)
        {
            if (validateVale == null || string.IsNullOrEmpty(zipPostalCode)) return false;

            var zip = zipPostalCode.ToLower();

            return validateVale.Any(item => zip.StartsWith(item.ToLower()));
        }

    }
}
